# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

library(optparse)
library(tidyverse)
library(igraph)
library(readxl)
# library(writexl)

option_list <- list(
  make_option("--config", default = "calculate_config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

edgeData <- read_csv("Network_Edges_for_Cytoscape.csv")

if (nrow(edgeData) == 0) {
  quit(status = 0)
}

graph <- graph_from_data_frame(edgeData, directed = F)
vector <- igraph::evcent(graph = graph, directed = F) %>%
  .$vector
nodeData <- read_csv("Network_Nodes_for_Cytoscape.csv") %>%
  rowwise() %>%
  do({
    result <- as_tibble(.)
    node <- result %>%
      .$Node
    result$degree <- igraph::degree(graph = graph, v = node)
    result$closeness <- igraph::closeness(graph = graph, vids = node)
    result$betweenness <- igraph::betweenness(graph = graph, v = node, directed = F)
    result
  }) %>%
  ungroup() %>%
  mutate(evcent = vector) %>%
  select(c("Node", "degree", "closeness", "betweenness", "evcent"))

write_csv(nodeData, str_c("Network_Nodes_for_Cytoscape.csv"))

outEdgeData <- edgeData %>%
  mutate(`|r|` = abs(r)) %>%
  mutate(`r>0` = (r > 0)) %>%
  mutate(`-ln (p)` = (-log(P))) %>%
  mutate(`-ln (P.adj)` = (-log(FDR))) %>%
  rename(P.adj = FDR)

write_tsv(outEdgeData, str_c("Network_Edges_for_Cytoscape.xls"))

write_graph(graph = graph,file ="Network_for_Cytoscape.gml",format = "gml")









